import os
import sys
import time
import json
import requests
# sys.path.insert(-1, "..")


# 获取当前文件的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 添加子工程的路径到 sys.path
sys.path.append(current_dir)

from handwriting import recognize_handwriting_content
from model_api import call_model_api, call_dianxin_api
from utils.config_utils import load_config
from utils.http_utils import post_request
from utils.log_utils import SimpleLogger
from dianxinApiSent import WritingOpenCorrectController
from openai import OpenAI

# from logserver import LogServer

# logger = LogServer(app='llm-server-correct', log_path="./log")
# logger.save_pid_to_file()  # for monitor
# log_filename = "llm-server-correct"
# logger.re_configure_logging(str(log_filename) + "_log.txt")
simple_logger = None
simple_logger = SimpleLogger('./log/correct_pipeline.log')

def get_model_name_from_config_file(config_file='config.json'):
    config = load_config(config_file)
    if config :
        print('model : ', config.get('model', 'gpt-4'))
        return config.get('model', 'gpt-4')
    else:
        print('fial to load config file.')
    return None

def get_prompt_template_from_config_file(config_file='config.json'):
    config = load_config(config_file)
    if config :
        #print('prompt template : ', config.get('prompt_template', '请输入要纠正的单词：'))
        prompt_template_for_high_score = config.get('prompt_template_for_high_score', '请输入要纠正的单词：')
        prompt_template_for_medium_score = config.get('prompt_template_for_medium_score', '请输入要纠正的单词：')
        prompt_template_for_low_score = config.get('prompt_template_for_low_score', '请输入要纠正的单词：')
        return prompt_template_for_high_score, prompt_template_for_medium_score, prompt_template_for_low_score
    #else:
    #    print('fial to load config file.')
    return None, None, None

def get_word_size_threshold_from_config_file(config_file='config.json'):
    config = load_config(config_file)
    if config :
        #print('prompt template : ', config.get('word_size_threshold', 500))
        word_size_low_threshold = config.get('word_size_low_threshold', 500)
        word_size_medium_threshold = config.get('word_size_medium_threshold', 600)
        return word_size_low_threshold, word_size_medium_threshold
    else:
        print('fial to load config file.')
    return 500, 600

def correction_pipeline(file_path, config_file='config.json', model_name=None, problem=''):
    # 读取配置文件中的模型名称
    # if model_name is None:
    #     model_name = get_model_name_from_config_file(config_file)

    # 读取prompt模板
    prompt_template_for_high_score, prompt_template_for_medium_score, prompt_template_for_low_score = get_prompt_template_from_config_file(config_file)

    # 识别手写作文的内容
    begin_time = time.time()
    recognized_word = recognize_handwriting_content(file_path)
    print('recognizeing time : ', time.time() - begin_time)
    print('recognized word size: ', len(recognized_word))
    print('recongniztion done.')
    if prompt_template_for_high_score is None or prompt_template_for_low_score is None:
        print('fial to load prompt template.')
        return None, None
    
    # 电信的接口和其他的不一样，需要单独处理
    if model_name == 'dianxin':
        print('start to call model api.')
        begin_time = time.time()
        correction_result = call_dianxin_api(problem, recognized_word)
        print('call_model_api time : ', time.time() - begin_time)
        selected_correction_result = None
        if correction_result is not None:
            selected_correction_result = dict()
            selected_correction_result['totalScore'] = correction_result['totalScore']
            selected_correction_result['contentScore'] = correction_result['contentScore']
            selected_correction_result['languageScore'] = correction_result['languageScore']
            selected_correction_result['structureScore'] = correction_result['structureScore']
            selected_correction_result['topicScore'] = correction_result['topicScore']
            selected_correction_result['percentageScore'] = correction_result['percentageScore']
            selected_correction_result['comment'] = correction_result['comment']
            selected_correction_result['expression'] = correction_result['expression']
            selected_correction_result['suggestion'] = correction_result['suggestion']
            selected_correction_result['improveArticle'] = correction_result['improveArticle']

        return selected_correction_result, recognized_word
    else:
        # 读取配置文件中的模型名称
        model_name = get_model_name_from_config_file(config_file)
    
    # 根据字数去使用不同的prompt模板
    #print('word size threshold : ', get_word_size_threshold_from_config_file(config_file))
    low_threshold, medium_threshold = get_word_size_threshold_from_config_file(config_file)
    if len(recognized_word) > medium_threshold:
        prompt_template = prompt_template_for_high_score
    elif len(recognized_word) <= medium_threshold and len(recognized_word) > low_threshold:
        prompt_template = prompt_template_for_medium_score
    else:
        prompt_template = prompt_template_for_low_score

    #print('prompt template : ', prompt_template)

    # 填充作文到prompt模板中
    prompt_template_with_essay = replace_placeholder(prompt_template, recognized_word)
    #print('prompt template with essay : ', prompt_template_with_essay)
    print('start to call model api.')
    # 调用模型API进行作文批改
    begin_time = time.time()
    correction_result = call_model_api(model_name, prompt_template_with_essay, api_key='')
    print('call_model_api time : ', time.time() - begin_time)
    return correction_result, recognized_word


def replace_placeholder(template, replacement):
    """
    替换模板字符串中的占位符

    参数:
    template (str): 包含占位符的字符串
    replacement (str): 用于替换占位符的字符串

    返回:
    str: 替换后的字符串
    """
    return template.replace("{}", replacement)

########################################################## 批改的基类 ##########################################################################

class Corrector:
    def __init__(self, model_name:str) -> None:
        '''
        构造函数
        '''
        self.model_name = model_name
    
    def correct(self, content, task='cn', problem=None):
        '''
        批改任务
        '''
        return ""
    
    def load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        # self.config = load_config(config_file)
        pass

    def _load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        try:
            with open(config_file, 'r', encoding='utf-8') as file:
                config = json.load(file)
                file.close()
            # return config.get('model', 'gpt-4')
            return config
        except Exception as e:
            print(e)
            return None
        

########################################################## 作文批改 ##########################################################################
class BaiduEssayCorrector(Corrector):
    '''
    使用百度的API进行作文批改
    '''
    def __init__(self, config_file:str) -> None:
        '''
        构造函数
        '''
        super().__init__(model_name='baidu')
        self.api_url = None
        self.prompt_template_for_high_score = None
        self.prompt_template_for_medium_score = None
        self.prompt_template_for_low_score = None
        self.low_threshold = 500
        self.medium_threshold = 600
        self.load_config(config_file)

    def correct(self, content, task='cn', problem=None):
        '''
        识别任务
        '''
        # print('config param : ', self.api_url)
        simple_logger.info("start to correct content with baidu model.")
        correction_result = self._correct(content, task, problem)
        simple_logger.info("correct content with baidu model done.")
        # 挑选一些我们想要的内容出来
        selected_correction_result = None
        if correction_result is not None:
            selected_correction_result = dict()
            keys = correction_result.keys()
            if 'score4' in keys:
                selected_correction_result['totalScore'] = correction_result['score4']
            else:
                selected_correction_result['totalScore'] = 0
            if 'score0' in keys:
                selected_correction_result['contentScore'] = round(correction_result['score0'] / 15.0 * 5)
            else:
                selected_correction_result['contentScore'] = 0
            if 'score1' in keys:
                selected_correction_result['languageScore'] = round(correction_result['score1']  / 15.0 * 5)
            else:
                selected_correction_result['languageScore'] = 0
            if 'score2' in keys:
                selected_correction_result['structureScore'] = round(correction_result['score2'] / 15.0 * 5)
            else:
                selected_correction_result['structureScore'] = 0
            if 'score3' in keys:
                selected_correction_result['topicScore'] = round(correction_result['score3'] / 15.0 * 5)
            else:
                selected_correction_result['topicScore'] = 0
            if 'score4' in keys:
                selected_correction_result['percentageScore'] = round(correction_result['score4'] / 60.0, 4)
            else:
                selected_correction_result['percentageScore'] = 0
            if 'comment' in keys:
                selected_correction_result['comment'] = correction_result['comment']
            else:
                selected_correction_result['comment'] = ""
            if 'expression' in keys:
                selected_correction_result['expression'] = correction_result['expression']
            else:
                selected_correction_result['expression'] =[]
            if 'suggestion' in keys:
                selected_correction_result['suggestion'] = correction_result['suggestion']
            else:
                selected_correction_result['suggestion'] = []
            if 'improveArticle' in keys:
                selected_correction_result['improveArticle'] = correction_result['improveArticle']
            else:
                selected_correction_result['improveArticle'] = ""
            if 'errorCorrection' in keys:
                selected_correction_result['errorCorrection'] = correction_result['errorCorrection']
            else:
                selected_correction_result['errorCorrection'] = []
        return selected_correction_result

    
    def _correct(self, content, task='cn', problem=None):
        
        if self.prompt_template_for_high_score is None or self.prompt_template_for_medium_score is None or \
            self.prompt_template_for_low_score is None:
            return None

        url = self.api_url + self._get_access_token()
        prompt = self._generate_prompt(content)
        payload = json.dumps({
            "messages": [
                {
                    "role": "user",
                    "content": prompt,
                }
            ],
            "temperature": 0.95,
            "top_p": 0.8,
            "penalty_score": 1,
            "disable_search": True,
            "stream":False,
            "enable_citation": False,
            "max_output_tokens": 100
        })
        headers = {
            'Content-Type': 'application/json'
        }

        result_json = None
        
        simple_logger.info("----------------------------------")
        simple_logger.info("start to call baidu model api.")
        response = post_request(url=url, headers=headers, data=payload)
        simple_logger.info("call baidu model api done.")
        simple_logger.info("----------------------------------")
        if response.status_code == 200 and response.json() is not None and "result" in response.json():
            result_json = None
            try :
                # if logger is not None:
                #     logger.logging("correct response text : " + response.text)
                #print(response.json()["result"])
                result_str = response.json()["result"]
                '''
                百度返回的数据结构如下，是一个字符串，需要转成json
                #  三个单引号json
                # {
                #     "score0": 10,
                #     "score1": 10,
                #     "score2": 12,
                #     "score3": 10,
                #     "score4": 42
                # }
                # 三个单引号
                '''
                
                if isinstance(result_str, str) and len(result_str) > 15:
                    # print('text : ', result_str[7:-3])
                    result_json = json.loads(result_str[7:-3])
                    # print(result_json)
                    # print(type(result_json))
                return result_json
            except Exception as e:
                # if logger is not None:
                #     logger.logging("correct response load Exception : " + e)
                simple_logger.error("correct response load Exception : " + e)
                return None

        else:
            return None

    def load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        print('loading config file.')
        config = self._load_config(config_file)
        if config is not None:
            self.api_url = config.get('baidu_predict_url')
            self.prompt_template_for_high_score = config.get('prompt_template_for_high_score', None)
            self.prompt_template_for_medium_score = config.get('prompt_template_for_medium_score', None)
            self.prompt_template_for_low_score = config.get('prompt_template_for_low_score', None)
            self.low_threshold = config.get('word_size_low_threshold', 500)
            self.medium_threshold = config.get('word_size_medium_threshold', 600)
        print('config param : ', self.api_url)

    def _get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": "nvGlKBt9yyh0kUMTQWVdArSR", "client_secret": "FJRNLCUDcHuOCoUz2qGEzyhgxC74mrNZ"}
        return str(requests.post(url, params=params).json().get("access_token"))
    
    def _generate_prompt(self, content):
        if len(content) > self.medium_threshold:
            prompt_template = self.prompt_template_for_high_score
        elif len(content) <= self.medium_threshold and len(content) > self.low_threshold:
            prompt_template = self.prompt_template_for_medium_score
        else:
            prompt_template = self.prompt_template_for_low_score

        return self._replace_placeholder(prompt_template, content)

    def _replace_placeholder(self, template, replacement):
        """
        替换模板字符串中的占位符

        参数:
        template (str): 包含占位符的字符串
        replacement (str): 用于替换占位符的字符串

        返回:
        str: 替换后的字符串
        """
        return template.replace("{}", replacement)
    


class DianxinEssayCorrector(Corrector):
    '''
    使用电信的API进行作文批改
    '''
    def __init__(self, config_file:str) -> None:
        '''
        构造函数
        '''
        super().__init__(model_name='dianxin')
        self.correct_cap_no = None
        self.load_config(config_file)
        print("correct_cap_no : ", self.correct_cap_no)
        self.controller = WritingOpenCorrectController(self.correct_cap_no)

    
    def correct(self, content, task='cn', problem=None, grade=None):
        '''
        批改任务
        '''
        try:

            simple_logger.info("----------------------------------")
            simple_logger.info("start to correct with dianxin model.")
            # 原始的批改结果
            correction_result = self._correct(content, task, problem, grade)
            simple_logger.info("correct with dianxin model done.")
            simple_logger.info("----------------------------------")
            
            # 挑选一些我们想要的内容出来
            selected_correction_result = None
            if correction_result is not None:
                selected_correction_result = dict()
                keys = correction_result.keys()
                if 'totalScore' in keys:
                    selected_correction_result['totalScore'] = correction_result['totalScore']
                else:
                    selected_correction_result['totalScore'] = 0
                if 'contentScore' in keys:
                    selected_correction_result['contentScore'] = correction_result['contentScore']
                else:
                    selected_correction_result['contentScore'] = 0
                if 'languageScore' in keys:
                    selected_correction_result['languageScore'] = correction_result['languageScore']
                else:
                    selected_correction_result['languageScore'] = 0
                if 'structureScore' in keys:
                    selected_correction_result['structureScore'] = correction_result['structureScore']
                else:
                    selected_correction_result['structureScore'] = 0
                if 'topicScore' in keys:
                    selected_correction_result['topicScore'] = correction_result['topicScore']
                else:
                    selected_correction_result['topicScore'] = 0
                if 'percentageScore' in keys:
                    selected_correction_result['percentageScore'] = correction_result['percentageScore']
                else:
                    selected_correction_result['percentageScore'] = 0
                if 'comment' in keys:
                    selected_correction_result['comment'] = correction_result['comment']
                else:
                    selected_correction_result['comment'] = ""
                if 'expression' in keys:
                    selected_correction_result['expression'] = correction_result['expression']
                else:
                    selected_correction_result['expression'] =[]
                if 'suggestion' in keys:
                    selected_correction_result['suggestion'] = correction_result['suggestion']
                else:
                    selected_correction_result['suggestion'] = []
                if 'improveArticle' in keys:
                    selected_correction_result['improveArticle'] = correction_result['improveArticle']
                else:
                    selected_correction_result['improveArticle'] = ""
                if 'errorCorrection' in keys:
                    selected_correction_result['errorCorrection'] = correction_result['errorCorrection']
                else:
                    selected_correction_result['errorCorrection'] = []
            return selected_correction_result
        except Exception as e:
            simple_logger.error("[ERROR] correct with dianxin model Exception : " + str(e))
            return None

    def _correct(self, content, task='cn', problem=None, grade=None):
        '''
        批改任务
        problem: 作文题目
        content:识别出来的作文内容
        task: 语文：cn;英语应用文：en-app；英语读后续写：en-con
        grade: 年级
        '''

        
        grade_list = {
            "一年级":"g1",
            "二年级":"g2",
            "三年级":"g3",
            "四年级":"g4",
            "五年级":"g5",
            "六年级":"g6",
            "七年级":"g7",
            "八年级":"g8",
            "九年级":"g9",
            "初一":"g7",
            "初二":"g8",
            "初三":"g9",
            "初四":"g9"
        }

        if grade is not None and grade != "" and grade in grade_list:
            grade = grade_list[grade]
        else:
            grade = ""

        simple_logger.info("to call dianxin api")
        result = None
        # 尝试3次
        for retry in range(3):
            original_result = self.controller.correct(content, problem, grade, task)
            if original_result is not None and original_result != "":
                break
        if original_result is not None and original_result != "":
            result_json = json.loads(original_result)
            if "code" in result_json and "result" in result_json:
                if result_json["code"] == 200:
                    result = result_json["result"]
        simple_logger.info("call dianxin api done")

        # print("result : ", result)
        return result
    
    def load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        '''
        加载配置文件
        '''
        print('loading config file.')
        config = self._load_config(config_file)
        if config is not None:
            self.correct_cap_no = config.get('correct_cap_no')

########################################################## 作文批改 ##########################################################################

########################################################## 公式批改 ##########################################################################


class BaiduFormulaCorrector(BaiduEssayCorrector):
    def __init__(self, config_file:str) -> None:
        '''
        构造函数
        '''
        super().__init__(config_file=config_file)
        self.api_url = None
        self.prompt_template_for_formula = None
        self.load_config(config_file)

    
    def correct(self, content, task='formula', problem=None):
        '''
        批改任务
        '''

        return self._correct(content)

    def _correct(self, content):
        '''
        批改任务
        '''
        if isinstance(content, list) and len(content) == 2:
            formula1 = content[0]
            formula2 = content[1]
            prompt = self._generate_prompt(formula1=formula1, formula2=formula2)
            print('prompt : ', prompt)

            url = self.api_url + self._get_access_token()
            payload = json.dumps({
                "messages": [
                    {
                        "role": "user",
                        "content": prompt,
                    }
                ],
                "temperature": 0.95,
                "top_p": 0.8,
                "penalty_score": 1,
                "disable_search": True,
                "stream":False,
                "enable_citation": False,
                "max_output_tokens": 50
            })
            headers = {
                'Content-Type': 'application/json'
            }

            response = post_request(url=url, headers=headers, data=payload)
            if response.status_code == 200 and response.json() is not None and "result" in response.json():
                #print(response.json()["result"])
                result_str = response.json()["result"]
                print('formula correct result : ', result_str)
                # 文心一言返回的是字符串，做了个简单的转换
                if isinstance(result_str, str):
                    if result_str == 'True':
                        return True
                    else:
                        return False

        return None
    
    def _generate_prompt(self, formula1, formula2):
        '''
        替换prompt模板里的formula1和formula2
        '''

        prompt_template = self.prompt_template_for_formula
        if prompt_template is not None:
            replace_formula1 = prompt_template.replace("formula1", formula1)
            prompt = replace_formula1.replace("formula2", formula2)
            return prompt
        return None

    
    def load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        print('loading config file.')
        config = self._load_config(config_file)
        if config is not None:
            self.api_url = config.get('baidu_predict_url')
            self.prompt_template_for_formula = config.get('prompt_template_for_formula', None)
        print('config param : ', self.api_url)


class DoubaoFormulaCorrector(BaiduEssayCorrector):
    def __init__(self, config_file:str) -> None:
        '''
        构造函数
        '''
        super().__init__(config_file=config_file)
        self.api_url = "https://ark.cn-beijing.volces.com/api/v3"
        self.api_key = "bef29778-8a39-419a-8268-8dc874927cb8"
        self.prompt_template_for_formula = None
        self.load_config(config_file)

    
    def correct(self, content, task='formula', problem=None):
        '''
        批改任务
        '''

        return self._correct(content)

    def _correct(self, content):
        '''
        批改任务
        '''
        if isinstance(content, list) and len(content) == 2:
            formula1 = content[0]
            formula2 = content[1]

            simple_logger.info("student answer & standard answer : {}, {}".format(formula1, formula2))

            prompt = self._generate_prompt(formula1=formula1, formula2=formula2)
            print('prompt : ', prompt)

            client = OpenAI(
                #api_key = os.environ.get("ARK_API_KEY"),
                api_key = self.api_key,
                base_url = self.api_url,
            )

            print("----- standard request -----")
            completion = client.chat.completions.create(
                model = "ep-20250626170523-l5v9f",  # doubao seed 1.6
                messages = [
                    {"role": "system", "content": "你是人工智能助手"},
                    {"role": "user", "content": prompt},
                ],
            )

            result = completion.choices[0].message.content
            simple_logger.info("doubao result : {}".format(result))

            # print('doubao result : ', result, type(result))

            if isinstance(result, str):
                # 文心一言返回的是字符串，做了个简单的转换
                if result == 'True':
                    return True
                else:
                    return False

        return None
    
    def _generate_prompt(self, formula1, formula2):
        '''
        替换prompt模板里的formula1和formula2
        '''

        prompt_template = self.prompt_template_for_formula
        if prompt_template is not None:
            replace_formula1 = prompt_template.replace("formula1", formula1)
            prompt = replace_formula1.replace("formula2", formula2)
            return prompt
        return None

    
    def load_config(self, config_file:str):
        '''
        加载配置文件
        '''
        print('loading config file.')
        config = self._load_config(config_file)
        if config is not None:
            # self.api_url = config.get('baidu_predict_url')
            self.prompt_template_for_formula = config.get('prompt_template_for_formula', None)
        # print('config param : ', self.api_url)


if __name__ == "__main__":
    #prompt_template = get_prompt_template_from_config_file()
    #print(replace_placeholder(prompt_template, 'test'))

    # file_path = "D:\\work\\code\\fx-business\\data\\8849324_0229201156_张旋_30.png"
    # #file_path = "D:\\me\\zuowen\\2193054\\53.5_李姗珊_240800020016.pdf"
    # correction_result, recognized_word = correction_pipeline(file_path)
    # print(correction_result)

    # dianxinEssayCorrector = DianxinEssayCorrector(config_file='config.json')
    # # baiduEssayCorrector = BaiduEssayCorrector(config_file='config.json')
    # problem = "导航仪在生活中的应用，让天下再无路盲。导航仪让驾驶人员在路途中视觉更加清晰，而不会迷失方向;导航仪让驾驶人员避免绕道，缩短行车时间;导航仪还为驾驶人员提供多种路径规划、智能规划路程服务…我们成长路上，也需要大生“导航仪”，也都有过被“导航仪”引领的经历与体验。"
    # content = '''四作文(50分)\n我的威人生的“导航，仪”\n我们在做一些没经验的事情时,总会绝弯路,所以就需要一些人来帮助我们，他们就像导航反一样引导着我们而我的事航仪,是我的父亲\n都说今年长的人的轻经验可贵，我的爸爸也这么想的，所以总是和我说他所认为对的事，但成却不这么觉得，我总想着他们的经验在飞速发展的社会中已经不管用了\n有一次我在买了一盒“草”，听老板说养个两三个月就会开始花,于是我就把它放在阳台上,每天盼着它快快长大，每天早上来，我一从床上下来就跑去阳台,给小草喷水用喷壶喷一下,它嫩绿的叶子上像撒了把银色的亮片一样,在晨光下被照得闪闪发亮；再喷见不，的水露顺着叶片流下盒中的泥里绿油油的像是要溢出颜料一样流满隆身这时父亲走过来,对我说：你这样每天给它喷水它会被淹死的,”我看看父亲,又看了一眼那盆草,说：“这里面的泥土都干干的,它怎么会被淹死”发出质疑后，我放下喷壶后就回了房间我完全不相信父亲的话,我认为他担心的太名了,小草没这么容易就死\n然而,过了不到一个月,到小草的叶片没有了“原来的嫩绿，换来的是枯黄这个代表不健康的色调我看着它犯了难,在想它有水有光有 \n养分，怎么就要枯了呢？父亲走过来，看到发黄的小草,皱了皱眉算说：如果再按原来的方法它装很快就会枯死的，你要三天喷一次水，这样它不会淹死”我看着那盆小草,想着目前也没有更好的方法了，于是就半信半疑地听取爸爸的建设议\n之后的每三天我都来喷一次水，不知不觉过了将近一个月的时间，小草恢复了它原来的色彩，仅细看,它身上开出了几朵白色的小花!春去是那么骄柔弱，又是那么坚强\n后来，那几朵小花长大了，变很坚忍有力我知道，没有父亲的指导，它根本不可能开花，父亲虽然老了，但他还是想要我很快地找到行走的路，他就是我人生路上的“导航化” \n'''
    # content = '''四作文(50分)\n我的人生“导航仪”\n一抹阳光如金丝般倾洒而下，落在青板石路，泛起点点光斑一缕清风荡漾起五彩的波露，阵阵花香弥漫空中，充盈着我的世界我漫步小路，感受春日的温暖，在这里我遇到石缝中开的花，那便是我的人生“导航仪”\n快节奏的学习生活似乎让我喘不过气，我疲惫的身驱摊软在书桌上，望着窗外的云霞，火红火红好似一团燃烧的烈火，我心中为之一颤，不禁流下泪水，打湿着桌上不佳的分数的试卷，或许是因为眼前的云霞大过耀眼，又或许是不佳的分数刺痛我的心\n回家路上，下起淅渐沥沥的雨雨，我垂头丧丧气地走着小路，天空密布的乌云似乎也在嘲笑着明下越大我攀白绚绚烂绽的花儿也被雨点打落了花头，一副快要枯萎了的样子我的鼻头不禁一酸，在花儿中看到自己的影子，刹那间，泪夺眶而出，打湿脸庞，一时分不清是雨是泪\n转身之际，忽瞥见角落中百缝里的花，我缓缓蹲下，映入眼帘的是一朵未闻花名的小花，我愣住了只见豆大的雨点亮不留情地砸落在它的身上，在风肆意地吹过它的身体，可那瘦小的身驱竟抵挡着所有狂风暴雨，顽强地战胜所有困难，挺立在石逢之中生生不息我赞叹它的顽强拼搏，它虽没 \n有别的花的艳丽，但它却有着“千磨万击还坚劲，任尔东西南北风的坚韧不拔，傲然挺立在石泽上，接受风雨的洗礼，成就更顽强的自己那一刻，它为我指引了前进的道路，给予我无限的力量，如同我人生的“导航仪”\n起身，心中忽觉轻松阳光穿透乌云，我的心中的路也渐渐明亮，正是石缝中米闻花名的花如“导航仪”一般指引我的方向，引领我走向远方我不由得加快了脚步，每一步都无比轻盈我执笔，奋笔疾书，不再畏惧困难，而迎难而上，书写自己美好未来\n阳光又洒满大地，我望着石缝中的花，与它共同呼吸新鲜的空气，沐浴着阳光，共同长成长石缝中开的花便是我的人生“导航仪”\n\n'''
    # task = 'cn'
    # grade = "g7"
    
    # correction_result = dianxinEssayCorrector.correct(content, task, problem, grade)
    # print('correction_result : ', correction_result)

    content = ["${\\left(-1, -1\\right)}$", "{（﹣1,﹣1）}"]
    # content = ["${0}$", "0"]
    # content = ["${BDAC}$", "${BDAC}$"]
    formula_corrector = DoubaoFormulaCorrector(config_file='config.json')
    result = formula_corrector.correct(content=content)
    print('result : ', result)
